package com.dongzili.binlog.common.binlogsynchronization;

import com.github.shyiko.mysql.binlog.event.EventType;
import com.google.api.client.util.Maps;
import lombok.Data;

import java.io.Serializable;
import java.util.Map;

import static com.github.shyiko.mysql.binlog.event.EventType.isDelete;
import static com.github.shyiko.mysql.binlog.event.EventType.isWrite;

/**
 * binlog对象
 **/
@Data
public class BinLogItem implements Serializable {
    private String dbTable;
    private EventType eventType;
    private Long timestamp = null;
    private Long serverId = null;
    // 存储字段-之前的值之后的值
    private Map<String, Serializable> before;
    private Map<String, Serializable> after;
    // 存储字段--类型
    private Map<String, Colum> colum;

    public BinLogItem() {

    }

    public BinLogItem(Serializable[] row, Map<String, Colum> columMap, EventType eventType) {
        this.eventType = eventType;
        this.colum = columMap;
        Map<String, Serializable> beOrAf = Maps.newHashMap();
        columMap.forEach((key, colum) -> {
//            if ("datetime".equalsIgnoreCase(colum.dataType)){
//
//            }
            Serializable serializable = row[colum.inx];
            if (serializable instanceof byte[]) {
                beOrAf.put(key, new String((byte[]) serializable));
            } else {
                beOrAf.put(key, serializable);
            }
        });

        // 写操作放after，删操作放before
        if (isWrite(eventType)) {
            this.after = beOrAf;
        } else if (isDelete(eventType)) {
            this.before = beOrAf;
        }


    }

    public BinLogItem(Map.Entry<Serializable[], Serializable[]> mapEntry, Map<String, Colum> columMap, EventType eventType) {
        this.eventType = eventType;
        this.colum = columMap;
        this.before = Maps.newHashMap();
        this.after = Maps.newHashMap();
        columMap.forEach((key, colum) -> {
            Serializable serializableKey = mapEntry.getKey()[colum.inx];
            if (serializableKey instanceof byte[]) {
                this.before.put(key, new String((byte[]) serializableKey));
            } else {
                this.before.put(key, serializableKey);
            }
            Serializable serializableValue = mapEntry.getValue()[colum.inx];
            if (serializableValue instanceof byte[]) {
                this.after.put(key, new String((byte[]) serializableValue));
            } else {
                this.after.put(key, serializableValue);
            }

        });

    }


}

